<template>
  <div id="checklist">
    <div v-show="pageInfo.cur === 1">
      <f7-block-title>基本信息</f7-block-title>
      <f7-list id="checklist-form-1" inline-labels form bg-color="white" class="no-margin">
        <f7-list-item title="县" smart-select :smart-select-params="{openIn: 'popover', closeOnSelect: true}">
          <select name="prefecture">
            <option v-for="x in place.filter(item => item.level === 1)" :value="x.id" selected>{{x.pname}}</option>
          </select>
        </f7-list-item>
        <f7-list-item title="乡镇名" smart-select :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '按汉字进行搜索'}">
          <select name="town" v-model="townid">
            <optgroup v-for="t in place.filter(item => item.level === 1)" :label="t.pname">
              <option v-for="p in place.filter(item => item.pid === t.id)" :value="p.id">{{p.pname}}</option>
            </optgroup>
          </select>
        </f7-list-item>
        <f7-list-item class="cunname" title="村名" smart-select :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '按汉字进行搜索'}">
          <select name="village" v-model="villageid">
            <optgroup v-for="v in place.filter(item => item.id === townid)" :label="v.pname">
              <option v-for="p in place.filter(item => item.pid === townid)" :value="p.id">{{p.pname}}</option>
            </optgroup>
          </select>
        </f7-list-item>
        <f7-list-item>
          <f7-label>时间</f7-label>
          <f7-input id="duchatime" type="text" name="time" readonly></f7-input>
        </f7-list-item>
      </f7-list>
      <f7-block-title>问题类别</f7-block-title>
      <f7-list id="checklist-form-2" form bg-color="white" class="no-margin">
        <f7-list-item title="基础设施（村部建设、道路硬化、电网改造、安全饮水、异地搬迁、危房改造等）">
          <f7-input type="textarea" name="infrastructure" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
        <f7-list-item title="政策落实（助学、医疗、产业帮扶政策等）">
          <f7-input type="textarea" name="implementation" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
        <f7-list-item title="精准识别（因病、残、学、灾、地、技等）">
          <f7-input type="textarea" name="accurate_recognition" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
      </f7-list>
    </div>
    <div v-show="pageInfo.cur === 2">
      <f7-block-title>问题类别</f7-block-title>
      <f7-list id="checklist-form-3" form bg-color="white" class="no-margin">
        <f7-list-item title="产业措施（养殖、种植、入股分红等）">
          <f7-input type="textarea" name="industry_measures" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
        <f7-list-item title="基础资料（扶贫档案、工作措施、会议记录等）">
          <f7-input type="textarea" name="basis_data" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
        <f7-list-item title="扶贫工作（入户、产业扶值、助学等）">
          <f7-input type="textarea" name="support_work" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
        <f7-list-item title="其它（来信、来访、典型发现等）">
          <f7-input type="textarea" name="other" class="bigtextarea" placeholder="问题内容"></f7-input>
        </f7-list-item>
      </f7-list>
    </div>
  </div>
</template>
<script>
import { f7BlockTitle, f7List, f7ListItem, f7Label, f7Input, f7Toggle, f7Row, f7Col, f7Button } from 'framework7-vue'
import { mapState, mapActions } from 'vuex'
import formatdate from 'utils/formatdate'
export default {
  components: {
    f7BlockTitle,
    f7List,
    f7ListItem,
    f7Label,
    f7Input,
    f7Toggle,
    f7Row,
    f7Col,
    f7Button
  },
  props: ['status'],
  computed: {
    ...mapState({
      user: state => state.user,
      pageInfo: state => state.page
    })
  },
  data() {
    return {
      townid: null,
      villageid: null,
      context: this.$f7route.context
    }
  },
  created() {

    this.hassave = true
    this.setDate(1)

    this.update_page({ count: 2, cur: 1 })
    this.$root.$off('gopage').$on('gopage', type => {
      if (type === 0) {
        if (this.pageInfo.cur <= 1) return
        this.pageInfo.cur -= 1
      } else {
        if (this.pageInfo.cur === this.pageInfo.count) return
        this.pageInfo.cur += 1
      }
    })

    this.$root.$off('save').$on('save', (camera, state = 0) => {
      let param = {}
      if (state <= 3) {
        for (var i = 1; i <= 3; i++) {
          const form = this.$f7.form.convertToData('#checklist-form-' + i)
          param = Object.assign(param, form)
        }
        if (!param.prefecture) {
          this.$f7.toast.show({ text: '请填写县' })
          return
        }
        if (!param.town) {
          this.$f7.toast.show({ text: '请填写乡镇' })
          return
        }
        if (!param.village) {
          this.$f7.toast.show({ text: '请填写村' })
          return
        }
        if (!param.time) {
          this.$f7.toast.show({ text: '请填写时间' })
          return
        }
      }
      this.saveData(param, camera, state)
    })

    this.$root.$off('submit').$on('submit', state => {
      let title = ''
      if (state === 3) {
        // 省督查组操作（确认），在入录里面完成
        title = '提交后变为待转办状态，且不可修改，可到待办功能里面进行转办处理'
      } else if (state === 4) {
        // 省督查组操作（转办），在待办里面完成
        title = '提交后变为已转办状态，将问题清单转办到县里面'
      } else if (state === 5) {
        title = '提交后变为待处理状态，将问题清单转办到处理员进行处理'
      } else if (state === 6) {
        title = '请确定问题已经处理'
      }
      this.$f7.dialog.confirm(title, '', () => {
        this.$root.$emit('save', () => {
        	this.$emit('update:status', state)
          if (state === 3) {
            this.$f7.dialog.alert('如需转办到县，请到待办功能里面处理', '提交成功')
          } else if (state === 4) {
            this.$f7.dialog.alert('已成功转办到县里面，如需查看进度，请到查看功能里面查看', '转办成功')
            this.$f7router.back()
          } else if (state === 5) {
            this.$f7.dialog.alert('已成功转办给处理员，如需查看进度，请到查看功能里面查看', '转办成功')
            this.$f7router.back()
          } else if (state === 6) {
            this.$f7.dialog.alert('', '处理成功')
            this.$f7router.back()
          }
        }, state)
      })
    })
  },
  mounted() {
    var self = this
    let minDate = new Date()
    minDate.setDate(minDate.getDate() - 1)
    this.$f7.calendar.create({
      inputEl: '#duchatime>input',
      openIn: 'customModal',
      closeOnSelect: true,
      routableModals: false,
      animate: false,
      minDate,
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      dayNamesShort: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      on: {
        open: calendar => {
          this.$$('#framework7-root').append('<div class="calendar-backdrop backdrop-in"></div>').find('.calendar-backdrop').click(function() {
            self.$$(this).remove()
            calendar.close()
          })
          const time = this.$$('#duchatime>input').val()
          if (!time) return
          calendar.setValue([time])
        },
        close: calendar => {
          this.$$('#framework7-root .calendar-backdrop').remove()
        }
      }
    })

    this.$f7.preloader.hide()
  },
  methods: {
    ...mapActions([
      'update_page'
    ]),
    async saveData(param, camera, state) {
      param.edittime = formatdate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      if (state === 3) {
      	param.state = 3
      	param.submittime = param.edittime
      } else if (state === 4) {
        param.state = 4
        param.transfertime1 = param.edittime
      } else if (state === 5) {
        param.state = 5
        param.transfertime2 = param.edittime
      } else if (state === 6) {
        param.state = 6
        param.overtime = param.edittime
      } else {
        param.state = state
      }
      // 转态处理
      if (state === 0 || state === 3) {
	      param.inspector = this.user.id    	
      }
      this.requestId && (param.id = this.requestId)
      const checklist = await this.request('/checklist', param)
      if (checklist.code === 1) {
        this.requestId = this.$root.requestId = checklist.data
        this.hassave = true
        if (!camera) {
          this.$f7.toast.show({ text: checklist.msg })
        } else {
          camera(this.requestId)
        }
      } else {
        this.$f7.dialog.confirm(checklist.msg, '', () => {
          // 跳转到查看页面 TODO
        })
      }
    },
    async setDate(page) {
      const { id, type } = this.context
      if ((id || this.requestId) && this.hassave) {
        const { data } = await this.request('/getdata', { id: id || this.requestId, type })
        if (!data && !data.id) return
        this.requestId = data.id
        this.viewdata = data
        this.hassave = false
      }
      if (!this.viewdata) return
      if (page === 1) {
        this.$f7.form.fillFromData('#checklist-form-1', {
          town: this.viewdata.town,
          time: formatdate(new Date(this.viewdata.time), 'yyyy-MM-dd')
        })
        this.$nextTick(() => {
          this.$f7.form.fillFromData('#checklist-form-1', {
            village: this.viewdata.village
          })
        })
        this.$f7.form.fillFromData('#checklist-form-2', {
          infrastructure: this.viewdata.infrastructure,
          implementation: this.viewdata.implementation,
          accurate_recognition: this.viewdata.accurate_recognition
        })
      } else if (page === 2) {
        this.$f7.form.fillFromData('#checklist-form-3', {
          industry_measures: this.viewdata.industry_measures,
          basis_data: this.viewdata.basis_data,
          support_work: this.viewdata.support_work,
          other: this.viewdata.other
        })
      }
    }
  },
  watch: {
    'townid': function() {
      this.villageid = ''
      this.$$('#checklist .cunname .item-after').html('')
    },
    'pageInfo.cur': function() {
      this.$nextTick(() => {
        this.setDate(this.pageInfo.cur)
        this.$$('#checklist').scrollTop(0)
      })
    }
  }
}
</script>
<style>
#checklist .item-title {
  white-space: normal;
}
</style>